//
//  SVGAnimateTransformElement.m
//  Shake and Bake
//
//  Created by Antoine Quint on 09/10/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "SVGAnimateTransformElement.h"
#import "CoreServices/CoreServices.h"

@implementation SVGAnimateTransformElement

- (void)initAnimationProperties:(NSDictionary *)attributes {

  // start by setting up the core properties
  [super initAnimationProperties:attributes];

  // now set up properties specific to <animateTransform>
	NSString *type = [attributes objectForKey:@"type"];
  NSString *to = [attributes objectForKey:@"to"];

  CATransform3D toTransform;

	int i;
	char currentChar;
  NSString *emptyString = @"";
	NSMutableString *currentParam = [NSMutableString string];
	NSMutableArray *params = [NSMutableArray arrayWithCapacity:0];
	for (i = 0; i < [to length]; i++) {
		currentChar = [to characterAtIndex:i];
		if (currentChar == ',' || currentChar == ' ') {
      if (![currentParam isEqualToString:emptyString]) {
  			[params addObject:currentParam];
  			currentParam = [NSMutableString string];
      }
		}
		else {
			[currentParam appendFormat:@"%c", currentChar];
		}
	}
	[params addObject:currentParam];

	// "type" attribute
	if ([type isEqualToString:@"translate"]) {
    float tx = [[params objectAtIndex:0] floatValue];
    float ty = 0.0f;
    if ([params count] == 2) {
      ty = [[params objectAtIndex:1] floatValue];
    }
    //NSLog(@"translate: %f, %f", tx, ty);
    toTransform = CATransform3DMakeTranslation(tx, ty, 0.0f);
	}
  else if ([type isEqualToString:@"rotate"]) {
    float angle = [[params objectAtIndex:0] floatValue] / 180.0 * pi;
    float cx = 0.0f;
    float cy = 0.0f;
    if ([params count] == 3) {
      cx = [[params objectAtIndex:1] floatValue];
      cy = [[params objectAtIndex:2] floatValue];
    }
    //NSLog(@"rotate: %f, %f, %f", angle, cx, cy);
    toTransform = CATransform3DIdentity;
    toTransform = CATransform3DTranslate(toTransform, cx, cy, 0.0f);
    toTransform = CATransform3DRotate(toTransform, angle, 0.0f, 0.0f, 1.0f);
    toTransform = CATransform3DTranslate(toTransform, -cx, -cy, 0.0f);
	}
  else if ([type isEqualToString:@"scale"]) {
    float sx = [[params objectAtIndex:0] floatValue];
    float sy = sx;
    if ([params count] == 2) {
      sy = [[params objectAtIndex:1] floatValue];
    }
    //NSLog(@"scale: %f, %f", sx, sy);
    toTransform = CATransform3DMakeScale(sx, sy, 1.0f);
	}

  //animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
  self.toValue = [NSValue valueWithCATransform3D:toTransform];

}

@end
